<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>成绩计算详情</title>
    <link rel="stylesheet" href="../utils/bootstrap-5.3.3-dist/css/bootstrap.min.css">
    <script src="../utils/bootstrap-5.3.3-dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../utils/icon/iconfont.css">
    <!--    时间选择器工具-->
    <link rel="stylesheet" href="../utils/flatpickr/flatpickr.min.css">
    <script src="../utils/flatpickr/flatpickr.min.js"></script>
    <link rel="stylesheet" href="../css/shared.css">
    <style>
        /*整体布局*/
        .result-layout {
            display: grid;
            grid-template-columns: 8fr 2fr;
            height: 720px;
        }

        /*左侧布局*/
        .rl-left {
            display: grid;
            grid-template-rows: 150px 500px 70px;
        }

        /*左上布局*/
        .rl-l-top {
            display: grid;
            grid-template-columns: 3fr 7fr;
        }

        .rl-l-top > div:first-child {
            display: flex;
            flex-direction: column;
            justify-content: space-evenly;
            padding-left: 5px;
            overflow-y: auto;
            border: 1px solid black;
        }

        /*左上右布局*/
        .rl-l-t-right {
            display: grid;
            grid-template-rows: 40% 20% 40%;
        }

        .rl-l-t-right > div:first-child {
            font-size: xx-large;
            font-weight: bold;
            text-align: center;
            padding-top: 10px;
        }

        .rl-l-t-right > div:nth-child(3) {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            gap: 50px;
            padding-left: 10px;
        }

        /*!*左上右上布局*!*/
        /*.rl-l-t-r-top{*/
        /*    display: grid;*/
        /*    grid-template-columns: 8fr 2fr;*/
        /*}*/
        /*右侧布局*/
        .rl-right {
            display: grid;
            grid-template-rows: 10% 5% 85%;
        }

        .rl-right > div:first-child {
            display: flex;
            align-items: center;
            justify-content: space-evenly;
        }

        .rl-right > div:nth-child(2) {
            font-weight: bold;
            text-align: center;
            font-size: large;
        }

        .rl-right > div:nth-child(3) {
            overflow-y: auto;
        }

        .rl-right > * {
            border: 1px solid black;
        }

        /*左边菜单布局*/
        .result-menu-element {
            background-color: #c6c7c8;
            border: 1px solid black;
            width: 90%;
            margin: 10px auto;

        }

        .result-menu-element > div:first-child {
            display: flex;
            align-items: center;
            justify-content: space-around;
        }

        /*
        鼠标变成可点击
         */
        .result-menu-element:hover {
            cursor: pointer;
        }

        table {
            margin-top: 5px;
        }

        /*表项限宽*/
        .table td {
            max-width: 15vw;
        }
        #details-table td{
            max-width: 150px;
        }
        #team-table td{
            max-width: 150px;
        }

        .algorithm-text {
            white-space: nowrap;
            max-width: 800px;
            overflow-x: auto;
            text-align: center;
            color: red;
        }

        .algorithm-example {
            display: flex;
            padding: 5px;
            align-items: center;
            justify-content: space-between;
        }

        /*路线设置布局*/
        .route-grid {
            display: grid;
            grid-template-rows: 50px 20px 50px;
            background-color: #c6c7c8;
            height: 120px;
            width: 700px;
        }

        .route-arrow {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
        }

        .route-arrow-margin {
            margin: 0 15px;
        }

        .route-button {
            display: block;
            margin: auto;
        }

        .route-option {
            display: grid;
            grid-template-columns: repeat(auto-fill, 50px);
            margin: auto 0;
        }

        .move-div {
            position: relative;
            z-index: 0;
        }

        .two-div-flex {
            display: flex;
            gap: 30px;
        }

        .img-size {
            max-width: 300px;
            max-height: 300px;
        }
    </style>
</head>
<body>
<div class="result-layout">
    <div class="rl-left">
        <div class="rl-l-top">
            <div id="rule-info">
                <div>
                    比赛时间：
                </div>
                <div>
                    组别：
                </div>
                <div>
                    规定路线：
                </div>
                <div>
                    限定时间：
                </div>
                <div>
                    商定算法：
                </div>
            </div>
            <div class="rl-l-t-right">
                <div>
                    标准距离-80m-个人-W22-结果1
                </div>
                <div>
                    <div class="algorithm-text" style="display:none;">
                        算法设置：
                    </div>
                </div>
                <div>
                    <!--                搜索框组件-->
                    <div style="width: 500px;">
                        <div class="input-group">
                            <input id="search-input" type="text" class="form-control" placeholder="可按选手姓名、号码、指卡号、成绩是否有效来搜索 . . .">
                            <button class="btn btn-outline-secondary iconfont" type="button"
                                    onclick="showSearch()">&#xe60a;
                            </button>
                        </div>
                    </div>
                    <button id="calculate-btn" class="btn btn-primary" style="display: none"
                            onclick="openEditAlgorithmDialog()">计算成绩
                    </button>
                    <button id="download-btn" class="btn btn-primary" style="display: none"
                            onclick="downloadResultTable()">导出成绩结果表
                    </button>
                </div>
            </div>
        </div>
        <div class="table-responsive">
            <table id="info-person-table" class="table table-sm table-bordered text-center" style="display: none">
                <thead>
                <tr>
                    <th>指卡号</th>
                    <th>选手号码</th>
                    <th>姓名</th>
                    <th>实际路线</th>
                    <th>用时</th>
                    <th>成绩状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="info-person-tbody" class="table-group-divider">
                </tbody>
            </table>
            <table id="info-relay-table" class="table table-sm table-bordered text-center" style="display: none">
                <thead>
                <tr>
                    <th>指卡号</th>
                    <th>接力队伍</th>
                    <th>参赛单位</th>
                    <th>实际路线</th>
                    <th>用时</th>
                    <th>成绩状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="info-relay-tbody" class="table-group-divider">
                </tbody>
            </table>
            <table id="result-relay-table" class="table table-sm table-bordered text-center" style="display: none">
                <thead>
                <tr>
                    <th>名次</th>
                    <th>指卡号</th>
                    <th>接力队伍</th>
                    <th>参赛单位</th>
                    <th>实际路线</th>
                    <th>用时</th>
                    <th>成绩状态</th>
                    <th>有效站数</th>
                </tr>
                </thead>
                <tbody id="result-relay-tbody" class="table-group-divider">
                </tbody>
            </table>
            <table id="result-person-table" class="table table-sm table-bordered text-center" style="display: none">
                <thead>
                <tr>
                    <th>名次</th>
                    <th>指卡号</th>
                    <th>选手号码</th>
                    <th>姓名</th>
                    <th>实际路线</th>
                    <th>用时</th>
                    <th>成绩状态</th>
                    <th>有效站数</th>
                </tr>
                </thead>
                <tbody id="result-person-tbody" class="table-group-divider">
                </tbody>
            </table>
        </div>
        <div>
            <!--    分页组件-->
            <ul class="pagination page-ul-flex" id="pagination">
            </ul>
        </div>
    </div>
    <div class="rl-right">
        <div>
            <button class="btn btn-primary" onclick="editAthleteGrade()">编辑选手数据</button>
            <button class="btn btn-primary" onclick="window.location.href='calculate-score.html'">返回</button>
        </div>
        <div>
            计算结果
        </div>
        <div>
            <!--            <div class="result-menu-element">-->
            <!--                <div>-->
            <!--                    <div>结果1</div>-->
            <!--                    <button class="btn btn-primary btn-sm">设置为最终结果</button>-->
            <!--                    <button class="btn btn-danger btn-sm">删除</button>-->
            <!--                </div>-->
            <!--                <div style="display:none;">-->
            <!--                    算法：有顺序，不能反悔，取第一个站开始算的最长有效子路线-->
            <!--                </div>-->
            <!--            </div>-->
        </div>
    </div>
</div>
<!--算法设置弹窗-->
<div id="edit-algorithm-dialog" class="my-dialog" style="display: none">
    <div class="my-dialog-header">
        <!--                    标题占位-->
        <span>算法设置</span>
        <button type="button" class="btn-close close-icon"
                onclick="closeEditAlgorithmDialog()"></button>
    </div>
    <div class="my-dialog-body">
        <!--        <div class="algorithm-example">-->
        <!--            <label><input type="radio" name="algorithm-type" value="1">算法1</label>-->
        <!--            <button class="btn btn-primary btn-sm">例子</button>-->
        <!--        </div>-->
    </div>
    <div class="my-dialog-footer">
        <small style="color: red;display: none">没有选择算法！</small>
        <button type="button" class="btn btn-secondary btn-sm my-dialog-ft-btn"
                onclick="closeEditAlgorithmDialog()">取消
        </button>
        <button type="button" class="btn btn-primary btn-sm my-dialog-ft-btn"
                onclick="submitEditAlgorithmDialog()">开始计算
        </button>
    </div>
</div>
<!--算法例子弹窗-->
<div id="algorithm-example-dialog" class="my-dialog" style="display: none">
    <div class="my-dialog-header">
        <!--                    标题占位-->
        <span></span>
        <button type="button" class="btn-close close-icon"
                onclick="closeDialogWithBackgroundId('algorithm-example-dialog','a-e-d-bg')"></button>
    </div>
    <div class="my-dialog-body">
        <p>

        </p>
    </div>
    <div class="my-dialog-footer">
    </div>
</div>
<!--编辑成绩信息弹窗-->
<div id="edit-info-dialog" class="my-dialog" style="display: none">
    <div class="my-dialog-header">
        <!--                    标题占位-->
        <span>编辑比赛信息</span>
        <button type="button" class="btn-close close-icon"
                onclick="closeEditInfoDialog()"></button>
    </div>
    <div class="my-dialog-body">
        <div class="input-layout" style="display: none">
            <div class="label-area">
                <label for="name">姓名：</label>
            </div>
            <div class="input-area">
                <input type="text" id="name" readonly>
            </div>
            <div class="err-area">
                <small style="color: red;"></small>
            </div>
        </div>
        <div class="input-layout" style="display: none">
            <div class="label-area">
                <label for="team-name">接力队伍：</label>
            </div>
            <div class="input-area">
                <input type="text" id="team-name" readonly>
            </div>
            <div class="err-area">
                <small style="color: red;"></small>
            </div>
        </div>
        <div class="input-layout" style="display: none">
            <div class="label-area">
                <label for="unit-name">参赛单位：</label>
            </div>
            <div class="input-area">
                <input type="text" id="unit-name" readonly>
            </div>
            <div class="err-area">
                <small style="color: red;"></small>
            </div>
        </div>
        <div class="input-layout">
            <div class="label-area">
                <p>成绩状态<span style="color:red;">*</span>：</p>
            </div>
            <div class="input-area">
                <label>
                    <input type="radio" name="status" value="1">
                    有效
                </label>
                <label>
                    <input type="radio" name="status" value="0">
                    无效
                </label>
            </div>
            <div class="err-area">
                <small style="color: red;"></small>
            </div>
        </div>
        <div class="input-layout">
            <div class="label-area">
                <label for="use-time">用时<span style="color:red;">*</span>：</label>
            </div>
            <div class="input-area">
                <input id="use-time" placeholder="时:分:秒">
                <label>
                    .
                    <input type="number" id="small-second" placeholder="00" min="0" max="99">
                </label>

            </div>
            <div class="err-area">
                <small style="color: red;"></small>
            </div>
        </div>
        <div class="input-layout">
            <div class="label-area">
                <label for="route">路线设置：</label>
            </div>
            <div class="input-area">
                <input type="text" id="route" style="width: 100%">
            </div>
            <div class="err-area">
                <small style="color: red;" id="route-err"></small>
            </div>
        </div>
        <div class="input-layout">
            <div class="label-area">
                <span>上传图片：</span>
            </div>
            <div class="input-area">
                <button class="btn btn-primary btn-sm" id="upload-picture" onclick="uploadPicture()">选择图片</button>
                (.jpg/.jpeg/.png/.webp,不超过10MB)<br>
            </div>
            <div class="err-area">
                <small style="color: red;" id="pic-err"></small>
            </div>
        </div>
        <div class="input-layout">
            <div class="label-area">
            </div>
            <div class="input-area">
                <img id="pic-img" class="img-size" src="" alt="图片未上传"/>
            </div>
            <div class="err-area">
                <small style="color: red;"></small>
            </div>
        </div>
        <div class="input-layout">
            <div class="label-area">
                <label for="description">备注(不大于500字)：</label>
            </div>
            <div class="input-area">
                <textarea id="description" name="description" style="width: 100%"
                          maxlength="500"></textarea>
            </div>
            <div class="err-area">
                <small style="color: red;"></small>
            </div>
        </div>
    </div>
    <div class="my-dialog-footer">
        <button type="button" class="btn btn-secondary btn-sm my-dialog-ft-btn"
                onclick="closeEditInfoDialog()">取消
        </button>
        <button type="button" class="btn btn-primary btn-sm my-dialog-ft-btn"
                onclick="submitEditInfoDialog()">确认
        </button>
    </div>
</div>
<!--成绩信息详情-->
<div id="show-info-dialog" class="my-dialog" style="display: none;">
    <div class="my-dialog-header">
        <!--                    标题占位-->
        <span>成绩详情</span>
        <button type="button" class="btn-close close-icon"
                onclick="closeShowInfoDialog()"></button>
    </div>
    <div class="my-dialog-body">
        <div style="margin-top: 5px;margin-left: 5px;display: none;">
            <label for="details-name">选手姓名：</label>
            <input type="text" id="details-name" style="width: 80%" readonly>
        </div>
        <div style="margin-top: 5px;margin-left: 5px;display: none;">
            <label for="details-team-name">接力队伍：</label>
            <input type="text" id="details-team-name" style="width: 80%" readonly>
        </div>
        <div style="margin-top: 5px;margin-left: 5px;display: none;">
            <label for="details-unit-name">参赛单位：</label>
            <input type="text" id="details-unit-name" style="width: 80%" readonly>
        </div>
        <div style="margin-left: 5px" class="two-div-flex">
            <div id="details-num" style="display: none;">选手号码：</div>
            <div id="details-card">指卡号：</div>
        </div>
        <div style="margin-left: 5px">
            <label for="details-route">实际路线：</label>
            <input type="text" id="details-route" style="width: 80%" readonly>
        </div>
        <div style="margin-left: 5px" class="two-div-flex">
            <div id="details-time">用时：</div>
            <div id="details-status">成绩状态：</div>
        </div>
        <div style="margin-left: 5px" class="table-responsive">
            打卡详情：
            <table id="details-table" class="table table-sm table-bordered text-center">
                <thead>
                <tr>
                    <th>指卡号</th>
                    <th>站号</th>
                    <th>打卡顺序</th>
                    <th>打卡时间</th>
                </tr>
                </thead>
                <tbody id="details-tbody" class="table-group-divider">
                </tbody>
            </table>
        </div>
        <div style="margin-left: 5px" class="table-responsive">
            打卡人员：
            <table id="team-table" class="table table-sm table-bordered text-center">
                <thead>
                <tr>
                    <th>姓名</th>
                    <th>选手号码</th>
                    <th>批次</th>
                    <th>指卡号</th>
                </tr>
                </thead>
                <tbody id="team-tbody" class="table-group-divider">
                </tbody>
            </table>
        </div>
        <div style="margin-left: 5px">
            图片：
        </div>
        <div style="margin-left: 5px">
            <img id="details-img" src="" class="img-size" alt="图片未上传"/>
        </div>
        <div style="margin-left: 5px;margin-top: 5px;" class="two-div-flex">
            <label for="details-description">备注：</label>
            <textarea id="details-description" name="description" style="width: 80%" readonly></textarea>
        </div>
    </div>
    <div class="my-dialog-footer">
        <button type="button" class="btn btn-primary btn-sm my-dialog-ft-btn"
                onclick="closeShowInfoDialog()">关闭
        </button>
    </div>
</div>
<script src="../js/pages.js"></script>
<script src="../api/urls.js"></script>
<script src="../js/dialog.js"></script>
<script src="../js/progress.js"></script>
<script>
    //在页面离开前删除ruleId
    // window.addEventListener('beforeunload',()=>{
    //    window.sessionStorage.removeItem("ruleId");
    // });
    //页码
    let pageNum = 1;
    //一页多少条
    let pageSize = 20;
    //总条数
    let total;
    //总页数
    let pages;
    //请求记录
    let records;
    //是否是比赛信息
    let isInfo;
    //是否是接力
    let isRelay;
    //规定路线
    let route = [];
    //项目id
    let projectId;
    //组别id
    let groupId;
    //算法id
    let algorithmId;
    //项目名
    let projectName;
    //更新id
    let updateId;

    /**
     * 打卡成绩详情
     */
    function openShowInfoDialog(record){
        let teamTable = document.getElementById("team-table");
        let name = document.getElementById("details-name");
        let card = document.getElementById("details-card");
        let num = document.getElementById("details-num");
        let description = document.getElementById("details-description");
        let detailsTbody = document.getElementById("details-tbody");
        let teamTbody = document.getElementById("team-tbody");
        let img = document.getElementById("details-img");
        let status = document.getElementById("details-status");
        let time = document.getElementById("details-time");
        let route = document.getElementById("details-route");
        let unitName = document.getElementById("details-unit-name");
        let teamName = document.getElementById("details-team-name");
        if(isRelay){
            teamTable.parentElement.style.removeProperty("display");
            name.parentElement.style.display="none";
            num.style.display="none";
            unitName.parentElement.style.removeProperty("display");
            teamName.parentElement.style.removeProperty("display");
            unitName.value=record.unitName;
            teamName.value=record.teamName;
            for (const resultTeamDto of record.resultTeamDtoList){
                let trElement = document.createElement("tr");
                let tdElement1 = document.createElement("td");
                tdElement1.textContent = resultTeamDto.athleteName;
                let tdElement2 = document.createElement("td");
                tdElement2.textContent = resultTeamDto.athleteNum;
                let tdElement3 = document.createElement("td");
                if(resultTeamDto.batchNum===2147483647){
                    tdElement3.textContent="替补";
                }else {
                    tdElement3.textContent = resultTeamDto.batchNum;
                }
                let tdElement4 = document.createElement("td");
                tdElement4.textContent=resultTeamDto.cardNum;
                trElement.append(tdElement1,tdElement2,tdElement3,tdElement4)
                teamTbody.append(trElement);
            }
        }else {
            teamTable.parentElement.style.display="none";
            name.parentElement.style.removeProperty("display");
            num.style.removeProperty("display");
            unitName.parentElement.style.display="none";
            teamName.parentElement.style.display="none";
            name.value=record.athleteName;
            num.textContent="选手号码："+record.athleteNum;
        }
        for (const details of record.detailsList){
            let trElement = document.createElement("tr");
            let tdElement1 = document.createElement("td");
            tdElement1.textContent = details.cardNumber;
            let tdElement2 = document.createElement("td");
            if (details.stationNumber == 0) {
                tdElement2.textContent = '起点'
            }else if (details.stationNumber >=1 && details.stationNumber <=10 ) {
                tdElement2.textContent = details.stationNumber
            }else if (details.stationNumber >=11 && details.stationNumber <=15 ) {
                tdElement2.textContent = 'F'+details.stationNumber%10
            }else if (details.stationNumber == 19) {
                tdElement2.textContent = 'S'
            }
            else if (details.stationNumber == 20) {
                tdElement2.textContent = 'MO'
            }
            else if (details.stationNumber == 99) {
                tdElement2.textContent = '终点'
            }

            let tdElement3 = document.createElement("td");
            tdElement3.textContent = details.order;
            let tdElement4 = document.createElement("td");
            tdElement4.textContent=details.clockTime.split('T')[0] + " " + details.clockTime.split('T')[1];
            
            trElement.append(tdElement1,tdElement2,tdElement3,tdElement4)
            detailsTbody.append(trElement);
        }
        card.textContent="指卡号："+record.cardNum;
        description.value=record.description;
        img.src=PICTURE_BASE_URL+record.picture;
        route.value=record.route;
        if(record.status===1){
            status.textContent="成绩状态：有效";
        }else {
            status.textContent="成绩状态：无效";
        }
        time.textContent="用时："+record.useTime;
        openDialog("show-info-dialog");
    }


    /**
     * 关闭成绩详情
     */
    function closeShowInfoDialog() {
        let name = document.getElementById("details-name");
        let card = document.getElementById("details-card");
        let num = document.getElementById("details-num");
        let description = document.getElementById("details-description");
        let detailsTbody = document.getElementById("details-tbody");
        let teamTbody = document.getElementById("team-tbody");
        let img = document.getElementById("details-img");
        let status = document.getElementById("details-status");
        let time = document.getElementById("details-time");
        let route = document.getElementById("details-route");
        let unitName = document.getElementById("details-unit-name");
        let teamName = document.getElementById("details-team-name");
        unitName.value=null;
        teamName.value=null;
        route.value=null;
        name.value=null;
        card.textContent="指卡号：";
        num.textContent="选手号码：";
        description.value=null;
        detailsTbody.innerHTML="";
        teamTbody.innerHTML="";
        img.src="";
        status.textContent="成绩状态：";
        time.textContent="用时："
        closeDialog("show-info-dialog");
    }

    /**
     * 上传图片
     */
    async function uploadPicture() {
        // 创建input标签
        let input = document.createElement('input');
        input.type = "file";
        input.accept = ".jpg,.jpeg,.png,.webp";
        input.style.display = "none";
        document.body.append(input);
        input.click();
        input.addEventListener("change", async () => {
            if (input.files && input.files.length !== 0) {
                const maxSize = 10 * 1024 * 1024;//10MB
                if (input.files[0].size > maxSize) {
                    let picErr = document.getElementById("pic-err");
                    picErr.textContent = "图片大小应该小于10MB";
                    return;
                }
                let formData = new FormData();
                formData.append("file", input.files[0]);
                formData.append("gradeId", updateId);
                await fetch(RESULT_URL + "/uploadPicture", {
                    method: "POST",
                    body: formData
                }).then(resp => resp.text())
                    .then(picUri => {
                        console.log(picUri)
                        if (picUri) {
                            let picture = document.getElementById("pic-img");
                            picture.src = PICTURE_BASE_URL + picUri;
                        }
                    });
            }
            input.remove();
        });
    }

    /**
     * 关闭编辑弹窗
     */
    function closeEditInfoDialog() {
        let err = document.getElementById("route-err");
        err.textContent = null;
        let picErr = document.getElementById("pic-err");
        picErr.textContent = null;
        let name = document.getElementById("name");
        let teamName = document.getElementById("team-name");
        let unitName = document.getElementById("unit-name");
        let description = document.getElementById("description");
        let status = document.querySelectorAll("input[name='status']");
        let route = document.getElementById("route");
        let time = document.getElementById("use-time");
        let sSecond = document.getElementById("small-second");
        sSecond.value=null;
        time.value=null;
        status[0].checked = false;
        status[1].checked = false;
        name.value = null;
        teamName.value = null;
        unitName.value = null;
        description.value = null;
        route.value = null;
        let uploadPic = document.getElementById("pic-img");
        uploadPic.src = "";
        //使用flatpickr自定义时间选择器
        window.flatpickr("#use-time", {
            enableTime: true, // 启用时间选择
            noCalendar: true, // 不显示日期选择器，只显示时间选择器
            enableSeconds: true, // 启用秒的选择
            time_24hr: true, // 使用24小时制
            dateFormat: "H:i:S", // 设置日期格式为仅包含时间（小时:分钟:秒）
        });
        closeDialog("edit-info-dialog");
    }

    /**
     * 校验修改的数据
     */
    function verifyInfo() {
        let rt = document.getElementById("route");
        let err = document.getElementById("route-err");
        let flag = true;
        if (rt.value) {
            if (rt.value.length > 100) {
                err.textContent = "路线长度不能大于100!";
                flag = false;
            }
            let split = rt.value.split("-");
           // for (const splitElement of split) {
          //      if (!route.includes(splitElement)) {
           //         err.textContent = "路线中有不符合规定路线的站点!";
           //         flag = false;
           //         break;
           //     }
           // }
        }
        return flag;
    }

    /**
     * 提交编辑弹窗
     */
    async function submitEditInfoDialog() {
        let err = document.getElementById("route-err");
        err.textContent = null;
        let picErr = document.getElementById("pic-err");
        picErr.textContent = null;
        if (!verifyInfo()) {
            return;
        }
        let description = document.getElementById("description");
        let status = document.querySelectorAll("input[name='status']");
        let route = document.getElementById("route");
        let smallSecond = document.getElementById("small-second");
        let useTime = document.getElementById("use-time");
        let reqBody = {};
        for (let status1 of status) {
            if (status1.checked) {
                reqBody.status = status1.value;
            }
        }
        reqBody.route = route.value;
        reqBody.description = description.value;
        reqBody.gradeId = updateId;
        if (smallSecond.value) {
            if (Number(smallSecond.value) < 10) {
                reqBody.time = useTime.value + ".0" + Number(smallSecond.value);
            } else {
                reqBody.time = useTime.value + "." + Number(smallSecond.value);
            }

        } else {
            if(useTime.value){
                reqBody.time = useTime.value + ".00";
            }
        }
        await fetch(GRADE_URL + "/editInfo", {
            method: "POST",
            headers: new Headers({"Content-Type": "application/json"}),
            body: JSON.stringify(reqBody)
        })
        closeEditInfoDialog();
        await showPage();
        await getResultMenu();
    }

    /**
     * 打开编辑弹窗
     */
    async function openEditInfoDialog(record) {
        let name = document.getElementById("name");
        let teamName = document.getElementById("team-name");
        let unitName = document.getElementById("unit-name");
        if (isRelay) {
            name.parentElement.parentElement.style.display = "none";
            teamName.parentElement.parentElement.style.removeProperty("display");
            unitName.parentElement.parentElement.style.removeProperty("display");
            teamName.value = record.teamName;
            unitName.value = record.unitName;
        } else {
            name.parentElement.parentElement.style.removeProperty("display");
            teamName.parentElement.parentElement.style.display = "none";
            unitName.parentElement.parentElement.style.display = "none";
            name.value = record.athleteName;
        }
        if (record.useTime) {
            let useTime = document.getElementById("use-time");
            useTime.value = record.useTime.split(".")[0];
            let smallSecond = document.getElementById("small-second");
            smallSecond.value = Number(record.useTime.split(".")[1]);
        }
        //使用flatpickr自定义时间选择器
        window.flatpickr("#use-time", {
            enableTime: true, // 启用时间选择
            noCalendar: true, // 不显示日期选择器，只显示时间选择器
            enableSeconds: true, // 启用秒的选择
            time_24hr: true, // 使用24小时制
            dateFormat: "H:i:S", // 设置日期格式为仅包含时间（小时:分钟:秒）
        });
        if (record.status === 1) {
            let status = document.querySelector("input[name='status'][value='1']");
            status.checked = true;
        } else {
            let status = document.querySelector("input[name='status'][value='0']");
            status.checked = true;
        }
        let route = document.getElementById("route");
        route.value = record.route;
        let description = document.getElementById("description");
        description.value = record.description;
        if (record.picture) {
            let uploadPic = document.getElementById("pic-img");
            uploadPic.src = PICTURE_BASE_URL + record.picture;
        }
        openDialog("edit-info-dialog");
    }

    /**
     * 点击编辑选手数据
     */
    function editAthleteGrade() {
        isInfo = true;
        let searchInput = document.getElementById("search-input");
        searchInput.value = null;
        let title = document.querySelector(".rl-l-t-right>div:first-child");
        title.textContent = projectName;
        showSearch();
    }

    /**
     * 打开算法设置弹窗
     */
    async function openEditAlgorithmDialog() {
        //请求算法数据
        let url = new URL(ALGORITHM_URL + "/getAlgorithmMenu");
        url.searchParams.set("ruleId", window.sessionStorage.getItem("ruleId"));
        await fetch(url).then(resp => resp.json()).then(result => {
            let dialogBody = document.querySelector("#edit-algorithm-dialog .my-dialog-body");
            for (const resultElement of result) {
                let div = document.createElement("div");
                div.classList.add("algorithm-example");
                let label = document.createElement("label");
                let input = document.createElement("input");
                input.type = "radio";
                input.name = "algorithm-type";
                input.value = resultElement.algorithmId;
                // let algorithmId = document.getElementById("edit-algorithm").dataset.algorithmId;
                // if(algorithmId&&Number(algorithmId)===resultElement.algorithmId){
                //     input.checked=true;
                // }
                label.append(input, resultElement.algorithmName);
                let button = document.createElement("button");
                button.classList.add("btn", "btn-primary", "btn-sm");
                button.textContent = "例子";
                button.addEventListener("click", () => {
                    let p = document.querySelector("#algorithm-example-dialog .my-dialog-body p");
                    p.innerHTML = resultElement.algorithmDescription;
                    openDialogWithBackgroundIdAndZIndex("algorithm-example-dialog", "a-e-d-bg", 13);
                });
                div.append(label, button);
                dialogBody.append(div);
            }
        })
        openDialogWithBackgroundIdAndZIndex("edit-algorithm-dialog", "edit-algorithm-bg", 11);
    }

    /**
     * 关闭算法设置弹窗
     */
    function closeEditAlgorithmDialog() {
        let element = document.querySelector("#edit-algorithm-dialog .my-dialog-body");
        element.innerHTML = "";
        let small = document.querySelector("#edit-algorithm-dialog>.my-dialog-footer>small");
        small.style.display = "none";
        closeDialogWithBackgroundId("edit-algorithm-dialog", "edit-algorithm-bg");
    }

    /**
     * 提交编辑算法弹窗
     */
    async function submitEditAlgorithmDialog() {
        let algorithmType = document.querySelector("#edit-algorithm-dialog input[name='algorithm-type']:checked");
        if (algorithmType) {
            //进行计算
            let url = new URL(RESULT_URL + "/calculateResult");
            url.searchParams.set("algorithmId", algorithmType.value);
            url.searchParams.set("ruleId", window.sessionStorage.getItem("ruleId"));
            await fetch(url, {
                method: "POST"
            });
            await getResultMenu();
            //点击菜单选项
            let resultE = document.querySelector(`div.result-menu-element[data-algorithm-id="${algorithmType.value}"]`);
            if (resultE != null) {
                resultE.click();
            }
            closeEditAlgorithmDialog();
        } else {
            let small = document.querySelector("#edit-algorithm-dialog>.my-dialog-footer>small");
            small.style.removeProperty("display");
        }
    }

    /**
     * 点击搜索
     */
    async function showSearch() {
        pageNum = 1;
        await showPage();
    }

    /**
     * 渲染比赛信息表格
     */
    function drawInfoTable(records) {
        let tableParent = document.querySelector(".table-responsive");
        for (let child of tableParent.children) {
            child.style.display = "none";
        }
        if (isRelay) {
            let infoRelayTable = document.getElementById("info-relay-table");
            infoRelayTable.style.removeProperty("display");
            let tableBody = document.getElementById("info-relay-tbody");
            tableBody.innerHTML = "";
            for (let record of records) {
                let trElement = document.createElement("tr");
                let tdElement1 = document.createElement("td");
                tdElement1.textContent = record.cardNum;
                let tdElement2 = document.createElement("td");
                tdElement2.textContent = record.teamName;
                let tdElement3 = document.createElement("td");
                tdElement3.textContent = record.unitName;
                let tdElement4 = document.createElement("td");
                tdElement4.textContent = record.route;
                let tdElement5 = document.createElement("td");
                tdElement5.textContent = record.useTime;
                let tdElement6 = document.createElement("td");
                if (record.status === 1) {
                    tdElement6.textContent = "有效";
                } else {
                    tdElement6.textContent = "无效";
                }
                let tdElement11 = document.createElement("td");
                let buttonElement1 = document.createElement("button");
                buttonElement1.classList.add("btn", "btn-primary", "btn-sm", "iconfont");
                buttonElement1.textContent = "\u{e6f7}修改";
                buttonElement1.addEventListener("click", async () => {
                    updateId = record.gradeId;
                    await openEditInfoDialog(record);
                });
                buttonElement1.style.marginRight = "10px";
                let buttonElement2 = document.createElement("button");
                buttonElement2.classList.add("btn", "btn-primary", "btn-sm", "iconfont");
                buttonElement2.textContent = "\u{e6f7}详情";
                buttonElement2.addEventListener("click", () => {
                    openShowInfoDialog(record);
                });
                tdElement11.append(buttonElement1, buttonElement2);
                trElement.append(tdElement1, tdElement2, tdElement3, tdElement4, tdElement5, tdElement6, tdElement11);
                tableBody.append(trElement);
            }
        } else {
            let infoPersonTable = document.getElementById("info-person-table");
            infoPersonTable.style.removeProperty("display");
            let tableBody = document.getElementById("info-person-tbody");
            tableBody.innerHTML = "";
            for (let record of records) {
                let trElement = document.createElement("tr");
                let tdElement1 = document.createElement("td");
                tdElement1.textContent = record.cardNum;
                let tdElement2 = document.createElement("td");
                tdElement2.textContent = record.athleteNum;
                let tdElement3 = document.createElement("td");
                tdElement3.textContent = record.athleteName;
                let tdElement4 = document.createElement("td");
                tdElement4.textContent = record.route;
                let tdElement5 = document.createElement("td");
                tdElement5.textContent = record.useTime;
                let tdElement6 = document.createElement("td");
                if (record.status === 1) {
                    tdElement6.textContent = "有效";
                } else {
                    tdElement6.textContent = "无效";
                }
                let tdElement11 = document.createElement("td");
                let buttonElement1 = document.createElement("button");
                buttonElement1.classList.add("btn", "btn-primary", "btn-sm", "iconfont");
                buttonElement1.textContent = "\u{e6f7}修改";
                buttonElement1.addEventListener("click", async () => {
                    updateId = record.gradeId;
                    await openEditInfoDialog(record);
                });
                buttonElement1.style.marginRight = "10px";
                let buttonElement2 = document.createElement("button");
                buttonElement2.classList.add("btn", "btn-primary", "btn-sm", "iconfont");
                buttonElement2.textContent = "\u{e6f7}详情";
                buttonElement2.addEventListener("click", () => {
                    openShowInfoDialog(record);
                });
                tdElement11.append(buttonElement1, buttonElement2);
                trElement.append(tdElement1, tdElement2, tdElement3, tdElement4, tdElement5, tdElement6, tdElement11);
                tableBody.append(trElement);
            }
        }

    }

    /**
     *渲染成绩表格
     */
    function drawResultTable(records) {
        let tableParent = document.querySelector(".table-responsive");
        for (let child of tableParent.children) {
            child.style.display = "none";
        }
        if (isRelay) {
            let resultRelayTable = document.getElementById("result-relay-table");
            resultRelayTable.style.removeProperty("display");
            let tableBody = document.getElementById("result-relay-tbody");
            tableBody.innerHTML = "";
            for (let record of records) {
                let trElement = document.createElement("tr");
                let tdElement1 = document.createElement("td");
                tdElement1.textContent = record.rank;
                let tdElement2 = document.createElement("td");
                tdElement2.textContent = record.cardNum;
                let tdElement3 = document.createElement("td");
                tdElement3.textContent = record.teamName;
                let tdElement4 = document.createElement("td");
                tdElement4.textContent = record.unitName;
                let tdElement5 = document.createElement("td");
                tdElement5.textContent = record.route;
                let tdElement6 = document.createElement("td");
                tdElement6.textContent = record.time;
                let tdElement7 = document.createElement("td");
                if (record.status === 1) {
                    tdElement7.textContent = "有效";
                } else {
                    tdElement7.textContent = "无效";
                }
                let tdElement8 = document.createElement("td");
                tdElement8.textContent = record.routeNum;
                trElement.append(tdElement1, tdElement2, tdElement3, tdElement4, tdElement5, tdElement6, tdElement7, tdElement8);
                tableBody.append(trElement);
            }
        } else {
            let resultPersonTable = document.getElementById("result-person-table");
            resultPersonTable.style.removeProperty("display");
            let tableBody = document.getElementById("result-person-tbody");
            tableBody.innerHTML = "";
            for (let record of records) {
                let trElement = document.createElement("tr");
                let tdElement1 = document.createElement("td");
                tdElement1.textContent = record.rank;
                let tdElement2 = document.createElement("td");
                tdElement2.textContent = record.cardNum;
                let tdElement3 = document.createElement("td");
                tdElement3.textContent = record.athleteNum;
                let tdElement4 = document.createElement("td");
                tdElement4.textContent = record.name;
                let tdElement5 = document.createElement("td");
                tdElement5.textContent = record.route;
                let tdElement6 = document.createElement("td");
                tdElement6.textContent = record.time;
                let tdElement7 = document.createElement("td");
                if (record.status === 1) {
                    tdElement7.textContent = "有效";
                } else {
                    tdElement7.textContent = "无效";
                }
                let tdElement8 = document.createElement("td");
                tdElement8.textContent = record.routeNum;
                trElement.append(tdElement1, tdElement2, tdElement3, tdElement4, tdElement5, tdElement6, tdElement7, tdElement8);
                tableBody.append(trElement);
            }
        }
    }

    //实现分页的方法
    async function getPage(pageNum, pageSize) {
        let searchInput = document.getElementById("search-input");
        let url;
        if (isInfo) {
            if (isRelay) {
                url = new URL(RESULT_URL + "/searchInfoRelayAll");
            } else {
                url = new URL(RESULT_URL + "/searchInfoPersonAll");
            }
        } else {
            if (isRelay) {
                url = new URL(RESULT_URL + "/searchResultRelayAll");
            } else {
                url = new URL(RESULT_URL + "/searchResultPersonAll");
            }

            url.searchParams.set("algorithmId", algorithmId);
        }
        url.searchParams.set("pageNum", pageNum);
        url.searchParams.set("pageSize", pageSize);
        url.searchParams.set("projectId", projectId);
        url.searchParams.set("groupId", groupId);
        if (searchInput.value && searchInput.value.trim()) {
            url.searchParams.set("searchAll", searchInput.value.trim());
        }
        await fetch(url).then(response => {
            if (response.ok && response.headers.get("Content-Type") === "application/json") {
                return response.json();
            } else {
                throw new Error(`未知相应状态 ${response.status}或Content-Type：${response.headers.get("Content-Type")}`);
            }
        }).then(pageInfo => {
            pages = pageInfo.pages;
            total = pageInfo.total;
            records = pageInfo.records;
            let calculateBtn = document.getElementById("calculate-btn");
            let downloadBtn = document.getElementById("download-btn");
            let algorithmText = document.querySelector(".algorithm-text");
            if (isInfo) {
                algorithmText.style.display = "none";
                calculateBtn.style.removeProperty("display");
                downloadBtn.style.display = "none";
                drawInfoTable(records);
            } else {
                algorithmText.style.removeProperty("display");
                downloadBtn.style.removeProperty("display");
                calculateBtn.style.display = "none";
                drawResultTable(records);
            }
        }).catch(error => {
            console.log("分页错误：", error);
        });
    }

    //上一页
    async function prePage() {
        pageNum = pageNum - 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    //下一页
    async function nextPage() {
        pageNum = pageNum + 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages)
    }

    //点击切换
    async function handlePage(page) {
        if (page !== pageNum) {
            pageNum = page
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);
        }

    }

    /**
     * 改变每页条数
     */
    async function changePageSize(value) {
        pageSize = Number(value);
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    // 创建分页组件
    async function showPage() {
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }


    /**
     *获取结果菜单
     */
    async function getResultMenu() {
        let url = new URL(RESULT_URL + "/getResultMenu");
        url.searchParams.set("ruleId", window.sessionStorage.getItem("ruleId"));
        await fetch(url).then(r => {
            return r.json()
        }).then(result => {
            let resultMenu = document.querySelector(".rl-right>div:last-child");
            resultMenu.innerHTML = "";
            let hasLast = false;
            let resultNum = 1;
            for (const resultElement of result) {
                let parent = document.createElement("div");
                parent.dataset.algorithmId = resultElement.algorithmId;
                parent.classList.add("result-menu-element")
                let div1 = document.createElement("div");
                let div2 = document.createElement("div");
                div2.textContent = "结果" + resultNum;
                resultNum++;
                let button1 = document.createElement("button");
                button1.classList.add("btn", "btn-primary", "btn-sm");
                if (resultElement.isLast) {
                    button1.textContent = "取消最终结果";
                    hasLast = true;
                    button1.addEventListener("click", async (evt) => {
                        evt.stopPropagation();
                        let url1 = new URL(ALGORITHM_URL + "/setLast");
                        url1.searchParams.set("algorithmId", resultElement.algorithmId);
                        url1.searchParams.set("isSet", false);
                        await fetch(url1, {
                            method: "POST"
                        });
                        await getResultMenu();
                    });
                } else {
                    button1.textContent = "设为最终结果";
                    button1.addEventListener("click", async (evt) => {
                        evt.stopPropagation();
                        let url1 = new URL(ALGORITHM_URL + "/setLast");
                        url1.searchParams.set("algorithmId", resultElement.algorithmId);
                        url1.searchParams.set("isSet", true);
                        await fetch(url1, {
                            method: "POST"
                        });
                        await getResultMenu();
                    })
                }
                let button2 = document.createElement("button");
                button2.classList.add("btn", "btn-danger", "btn-sm");
                button2.textContent = "删除";
                button2.addEventListener("click", async (evt) => {
                    evt.stopPropagation();
                    let url1 = new URL(RESULT_URL + DELETE_URL);
                    url1.searchParams.set("algorithmId", resultElement.algorithmId);
                    await fetch(url1, {
                        method: "POST"
                    });
                    await getResultMenu();
                    let editButton = document.querySelector(".rl-right>div>button:first-child");
                    editButton.click();
                })
                if (resultElement.isLast) {
                    button2.disabled = true;
                }
                div1.append(div2, button1, button2);
                let div3 = document.createElement("div");
                div3.style.display = "none";
                div3.textContent = "算法：" + resultElement.algorithmName;
                parent.append(div1, div3);
                parent.addEventListener("mouseenter", () => {
                    parent.lastElementChild.removeAttribute("style");
                });
                parent.addEventListener("mouseleave", () => {
                    parent.lastElementChild.style.display = "none";
                });
                parent.addEventListener("click", () => {
                    let algorithmText = document.querySelector(".algorithm-text");
                    algorithmText.textContent = "算法设置：" + resultElement.algorithmName;
                    isInfo = false;
                    algorithmId = resultElement.algorithmId;
                    let searchInput = document.getElementById("search-input");
                    searchInput.value = null;
                    let title = document.querySelector(".rl-l-t-right>div:first-child");
                    title.textContent = projectName + "-" + div2.textContent;
                    showSearch();
                })
                resultMenu.append(parent);
            }
            if (hasLast) {
                for (let child of resultMenu.children) {
                    if (child.firstElementChild.children[1].textContent === "设为最终结果") {
                        child.firstElementChild.children[1].disabled = true;
                    }
                }
            }
        });
    }

    /**
     * 获取比赛信息
     */
    async function getRuleInfo() {
        let url = new URL(RULE_URL + "/getRuleInfo");
        url.searchParams.set("ruleId", window.sessionStorage.getItem("ruleId"));
        await fetch(url).then(resp => resp.json())
            .then(result => {
                let ruleInfo = document.getElementById("rule-info");
                ruleInfo.children[0].textContent = "比赛时间：" + result.startTime.split("T")[0] +
                    " " + result.startTime.split("T")[1];
                ruleInfo.children[1].textContent = "组别：" + result.groupName;
                ruleInfo.children[2].textContent = "规定路线：" + result.route;
                if (result.route && result.route.length > 0) {
                    route = result.route.split("-");
                }
                ruleInfo.children[3].textContent = "限定时间：" + result.limitTime;
                ruleInfo.children[4].textContent = "商定算法：" + result.algorithmName;
                isRelay = result.isRelay;
                projectId = result.projectId;
                groupId = result.groupId;
                let title = document.querySelector(".rl-l-t-right>div:first-child");
                title.textContent = result.projectName + "-" + result.groupName;
                projectName = result.projectName + "-" + result.groupName;
            });
    }

    async function downloadResultTable() {
        let url1 = new URL(RESULT_URL + "/downloadResultTable");
        url1.searchParams.set("algorithmId", algorithmId);
        url1.searchParams.set("projectId", projectId);
        url1.searchParams.set("groupId", groupId);
        url1.searchParams.set("isRelay", isRelay);
        await fetch(url1).then(resp => {
            return resp.blob();
        }).then(blob => {
            // 创建一个指向 Blob 的 URL
            const url = window.URL.createObjectURL(blob);

            // 创建 <a> 元素
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = '导出成绩结果表.xlsx'; // 设置下载的文件名

            // 添加 <a> 到文档中，并触发点击事件
            document.body.appendChild(a);
            a.click();

            // 清理资源
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        });
    }

    if (window.sessionStorage.getItem("competitionId") && window.sessionStorage.getItem("progress") &&
        Number(window.sessionStorage.getItem("progress")) >= CALCULATE_SCORE_PROGRESS &&
        window.sessionStorage.getItem("ruleId")) {
        (async () => {
            isInfo = true;
            await getRuleInfo();
            await getResultMenu();
            await showPage();
        })();
    } else {
        window.location.replace("index.html");
    }
</script>
</body>
</html>